package controllers

import (
	"TeacherManager/common"
	"TeacherManager/models"
	"TeacherManager/system"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/utrack/gin-csrf"
	"strconv"
	"strings"
)

/**
* Created by LONG  on 2018/5/25.
 */

func CheckUser(c *gin.Context) {
	userid := c.PostForm("userid")
	password := c.PostForm("password")
	fmt.Println(userid)
	fmt.Println(password)
	var err error
	if len(userid) > 0 && len(password) > 0 {
		var user *models.User
		user, err = models.GetUser(userid)
		encrypwd := common.Md5(user.Email + password)
		if strings.Compare(user.Password, encrypwd) == 0 {
			c.JSON(http.StatusOK, gin.H{
				"succeed": true,
				"message": "验证成功",
			})
			return
		}

		err = errors.New("密码错误")

	} else {
		err = errors.New("密码不能为空")
	}

	c.JSON(http.StatusOK, gin.H{
		"succeed": false,
		"message": err.Error(),
	})
}
func SigninGet(c *gin.Context) {
	config := system.GetConfiguration()
	c.Set("csrfSecret", config.SessionSecret)
	token := csrf.GetToken(c)
	fmt.Println(token)
	c.HTML(http.StatusOK, "auth/signin.html", gin.H{
		"csrf": token,
	})
}

func SignupGet(c *gin.Context) {
	c.HTML(http.StatusOK, "auth/signup.html", nil)
}
func SignupPost(c *gin.Context) {
	email := c.PostForm("email")
	password := c.PostForm("password")
	user := &models.User{
		Email:    email,
		Password: password,
		IsAdmin:  true,
	}
	var err error
	if len(user.Email) == 0 || len(user.Password) == 0 {
		err = errors.New("email or password cannot be null.")
	} else {
		user.Password = common.Md5(user.Email + user.Password)
		err = user.Insert()
		if err == nil {
			c.JSON(http.StatusOK, gin.H{
				"succeed": true,
			})
			return
		} else {
			err = errors.New("email already exists.")
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"succeed": false,
		"message": err.Error(),
	})
}

func setCookies(c *gin.Context, delete bool, items ...string) {
	cookietime, _ := strconv.Atoi(system.GetConfiguration().CookieTime)
	pwdtem := []byte(items[1] + system.GetConfiguration().SessionSecret)
	pwd := base64.StdEncoding.EncodeToString(pwdtem)
	if delete {
		c.SetCookie("uname", items[0], -1, "", "localhost", false, false)
		c.SetCookie("pwd", pwd, -1, "", "localhost", false, false)
		c.SetCookie("rem", "false", -1, "", "localhost", false, false)
	} else {
		c.SetCookie("uname", items[0], cookietime, "", "localhost", false, false)
		c.SetCookie("pwd", pwd, cookietime, "", "localhost", false, false)
		c.SetCookie("rem", "true", cookietime, "", "localhost", false, false)
	}

}
func SigninPost(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	remember := c.PostForm("remember")
	fmt.Println(username)
	fmt.Println(password)
	fmt.Println(remember)

	var err error
	if len(username) > 0 && len(password) > 0 {
		var user *models.User
		user, err = models.GetUserByUsername(username)
		fmt.Println(user, err)

		if err == nil && user.Password == common.Md5(username+password) {
			if strings.Compare(remember, "true") == 0 {
				setCookies(c, false, username, password)
			} else {
				setCookies(c, true, username, password)
			}
			s := sessions.Default(c)
			s.Clear()
			s.Set(SESSION_KEY, user.ID)
			s.Save()
			if user.IsAdmin {

				c.Redirect(http.StatusMovedPermanently, "/admin/index")
			} else {
				c.Redirect(http.StatusOK, "/signin")
			}
			return

		} else {
			err = errors.New("invalid username or password.")
		}
	} else {
		err = errors.New("username or password cannot be null.")
	}

	token := csrf.GetToken(c)
	fmt.Println(token)
	c.HTML(http.StatusOK, "auth/signin.html", gin.H{
		"message": err.Error(),
		"csrf":    token,
	})
}
